package com.meilai.project.service.administration.goods.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.administration.goods.GoodsPutStorageDTO;
import com.meilai.project.entity.administration.goods.GoodsPutStorage;
import com.meilai.project.entity.administration.goods.GoodsStorageChangeRecord;
import com.meilai.project.entity.administration.goods.GoodsStorageManage;
import com.meilai.project.entity.administration.goods.GoodsType;
import com.meilai.project.entity.business.sale.BillSaleGroup;
import com.meilai.project.entity.business.sale.BillSaleGroupRelation;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.administration.goods.GoodsPutStorageMapper;
import com.meilai.project.mapper.business.sale.BillSaleMapper;
import com.meilai.project.service.administration.goods.GoodsPutStorageService;
import com.meilai.project.service.administration.goods.GoodsStorageChangeRecordService;
import com.meilai.project.service.administration.goods.GoodsStorageManageService;
import com.meilai.project.service.administration.goods.GoodsTypeService;
import com.meilai.project.service.business.sale.BillSaleGroupRelationService;
import com.meilai.project.service.business.sale.BillSaleGroupService;
import com.meilai.project.vo.administration.goods.GoodsPutStorageVO;
import com.meilai.project.vo.business.sale.BillSaleGroupVO;
import com.meilai.project.vo.business.sale.BillSaleVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ykb
 * @date 2022/2/12 20:19
 */
@Service
@Log4j2
public class GoodsPutStorageServiceImpl extends ServiceImpl<GoodsPutStorageMapper, GoodsPutStorage> implements GoodsPutStorageService {

    @Autowired
    private GoodsStorageManageService goodsStorageManageService;

    @Autowired
    private BillSaleGroupService billSaleGroupService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private BillSaleGroupRelationService billSaleGroupRelationService;

    @Autowired
    private BillSaleMapper billSaleMapper;

    @Autowired
    private GoodsStorageChangeRecordService goodsStorageChangeRecordService;

    @Override
    public Page<GoodsPutStorageVO> selectPageList(Integer current_page, Integer page_size, GoodsPutStorageDTO searchDTO) {
        Page<GoodsPutStorageVO> page = new Page<>(current_page, page_size);
        List<GoodsPutStorageVO> list = baseMapper.selectPageList(page, searchDTO);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> group_id_list = list.stream().map(GoodsPutStorageVO::getGroup_id).collect(Collectors.toList());
            List<BillSaleGroupRelation> relationList = billSaleGroupRelationService.list(Wrappers.<BillSaleGroupRelation>lambdaQuery().in(BillSaleGroupRelation::getGroup_id, group_id_list));
            Map<Long, List<Long>> group_map = relationList.stream().collect(Collectors.groupingBy(BillSaleGroupRelation::getGroup_id, Collectors.mapping(BillSaleGroupRelation::getBill_sale_id, Collectors.toList())));
            List<Long> bill_sale_ids = relationList.stream().map(BillSaleGroupRelation::getBill_sale_id).collect(Collectors.toList());
            // 查询销售单数据
            list = list.stream().map(item -> {
                GoodsPutStorageVO vo = new GoodsPutStorageVO();
                BeanUtils.copyProperties(item, vo);
                List<Long> ids = group_map.get(vo.getGroup_id());
                if (CollectionUtils.isEmpty(ids)) {
                    vo.setBillSaleVOList(new ArrayList<>());
                } else {
                    List<BillSaleVO> billSaleVOS = billSaleMapper.selectListOfIds(bill_sale_ids);
                    List<BillSaleVO> collect = billSaleVOS.stream().filter(tmp -> ids.contains(tmp.getId())).collect(Collectors.toList());
                    vo.setBillSaleVOList(collect);
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return page.setRecords(list);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addOne(GoodsPutStorageDTO dto) {
        // 添加库存
        if (StringUtils.isNotEmpty(dto.getGoods_type_name())) {
            GoodsType one = goodsTypeService.getOne(Wrappers.<GoodsType>lambdaQuery().eq(GoodsType::getName, dto.getGoods_type_name()));
            if (one == null) {
                // 新建类型
                one = new GoodsType();
                one.setName(dto.getGoods_type_name());
                goodsTypeService.save(one);
                dto.setGoods_type_id(one.getId());
            } else {
                dto.setGoods_type_id(one.getId());
            }
            // 保存入库记录
            GoodsPutStorage storage = new GoodsPutStorage();
            BeanUtils.copyProperties(dto, storage);
            this.save(storage);
            // 添加库存变化记录
            GoodsStorageChangeRecord record = new GoodsStorageChangeRecord();
            record.setType(1);
            record.setChange_time(LocalDateTime.now());
            record.setOperator_id(dto.getUser_id());
            record.setGoods_type_id(dto.getGoods_type_id());
            record.setChange_number(dto.getNumber());
            record.setData_id(storage.getId());
            // 添加库存量
            GoodsStorageManage storageManage = goodsStorageManageService.getOne(Wrappers.<GoodsStorageManage>lambdaQuery().eq(GoodsStorageManage::getGoods_type_id, dto.getGoods_type_id()));
            if (storageManage == null) {
                storageManage = new GoodsStorageManage();
                storageManage.setStorage_number(dto.getNumber());
                storageManage.setGoods_type_id(dto.getGoods_type_id());
                storageManage.setLock_number(0L);
                // 库存记录
                record.setBefore_change_number(0L);
                record.setAfter_change_number(dto.getNumber());
                return goodsStorageChangeRecordService.save(record) && goodsStorageManageService.save(storageManage);
            } else {
                storageManage.setStorage_number(storageManage.getStorage_number() + dto.getNumber());
                record.setBefore_change_number(storageManage.getStorage_number());
                record.setAfter_change_number(storageManage.getStorage_number() + dto.getNumber());
                return goodsStorageChangeRecordService.save(record) && goodsStorageManageService.updateById(storageManage);
            }
        } else {
            throw new CommonException("物品名称不能为空");
        }
    }

    @Override
    public GoodsPutStorageVO getOneById(Long id) {
        GoodsPutStorageVO vo = baseMapper.getOneById(id);
        if (vo == null) {
            throw new CommonException("数据不存在");
        }
        List<BillSaleGroupRelation> relationList = billSaleGroupRelationService.list(Wrappers.<BillSaleGroupRelation>lambdaQuery().eq(BillSaleGroupRelation::getGroup_id, vo.getGroup_id()));
        List<Long> bill_sale_ids = relationList.stream().map(BillSaleGroupRelation::getBill_sale_id).collect(Collectors.toList());
        // 查询销售单数据
        if (CollectionUtils.isEmpty(bill_sale_ids)) {
            vo.setBillSaleVOList(new ArrayList<>());
        } else {
            List<BillSaleVO> billSaleVOS = billSaleMapper.selectListOfIds(bill_sale_ids);
            List<BillSaleVO> collect = billSaleVOS.stream().filter(tmp -> bill_sale_ids.contains(tmp.getId())).collect(Collectors.toList());
            vo.setBillSaleVOList(collect);
        }
        return vo;
    }

    //    @Override
//    @Transactional
//    public Boolean editOne(GoodsPutStorageDTO dto) {
//        GoodsPutStorage temp = getById(dto.getId());
//        if (temp == null) return false;
//        GoodsPutStorage goodsPutStorage = new GoodsPutStorage();
//        BeanUtils.copyProperties(dto, goodsPutStorage);
//        //更新库存表
//        Long old_number = temp.getNumber();
//        Long new_number = dto.getNumber();
//        boolean flag = true;
//        if (old_number > new_number) {
//            flag = goodsStorageManageService.checkGoodsStorage(old_number - new_number, temp.getSupplier_id(), temp.getSupplier_goods_id());
//        }
//        if (flag) {
//            GoodsStorageManageDTO goodsStorageManageDTO = new GoodsStorageManageDTO();
//            goodsStorageManageDTO.setSupplier_id(temp.getSupplier_id());
//            goodsStorageManageDTO.setSupplier_goods_id(temp.getSupplier_goods_id());
//            goodsStorageManageDTO.setPut_number(-new_number);
//            goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//            return updateById(goodsPutStorage) && flag;
//        } else {
//            throw new CommonException("原物品数量已在出库中，无法减少数量，请联系管理员");
//        }
//        return true;
//    }


//    @Override
//    @Transactional
//    public Boolean delete(Long id) {
//        LocalDateTime now = LocalDateTime.now();
//        GoodsPutStorage temp = getById(id);
//        if (temp == null) return false;
//        GoodsPutStorage goodsPutStorage = new GoodsPutStorage();
//        goodsPutStorage.setId(id);
//        goodsPutStorage.setDeleted_at(now);
//        //更新库存表
//        Long number = temp.getNumber();
//
//        boolean flag = goodsStorageManageService.checkGoodsStorage(number, temp.getSupplier_id(), temp.getSupplier_goods_id());
//        if (flag) {
//            GoodsStorageManageDTO goodsStorageManageDTO = new GoodsStorageManageDTO();
//            goodsStorageManageDTO.setSupplier_id(temp.getSupplier_id());
//            goodsStorageManageDTO.setSupplier_goods_id(temp.getSupplier_goods_id());
//            goodsStorageManageDTO.setPut_number(-number);
//            goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//            return updateById(goodsPutStorage);
//        } else {
//            throw new CommonException("物品数量已在出库中，无法删除入库单，请联系管理员");
//        }
//        return true;
//    }

    @Override
    public List<BillSaleGroupVO> getList() {
        List<BillSaleGroup> result = billSaleGroupService.list();
        if (CollectionUtils.isEmpty(result)) {
            return new ArrayList<>();
        } else {
            List<Long> group_id_list = result.stream().map(BillSaleGroup::getId).collect(Collectors.toList());
            List<BillSaleGroupRelation> relationList = billSaleGroupRelationService.list(Wrappers.<BillSaleGroupRelation>lambdaQuery().in(BillSaleGroupRelation::getGroup_id, group_id_list));
            Map<Long, List<Long>> group_map = relationList.stream().collect(Collectors.groupingBy(BillSaleGroupRelation::getGroup_id, Collectors.mapping(BillSaleGroupRelation::getBill_sale_id, Collectors.toList())));
            List<Long> bill_sale_ids = relationList.stream().map(BillSaleGroupRelation::getBill_sale_id).collect(Collectors.toList());
            // 查询销售单数据
            List<BillSaleVO> billSaleVOS = billSaleMapper.selectListOfIds(bill_sale_ids);
            return result.stream().map(item -> {
                BillSaleGroupVO vo = new BillSaleGroupVO();
                BeanUtils.copyProperties(item, vo);
                List<Long> ids = group_map.get(vo.getId());
                if (CollectionUtils.isEmpty(ids)) {
                    vo.setSaleVOList(new ArrayList<>());
                } else {
                    List<BillSaleVO> collect = billSaleVOS.stream().filter(tmp -> ids.contains(tmp.getId())).collect(Collectors.toList());
                    vo.setSaleVOList(collect);
                }
                return vo;
            }).collect(Collectors.toList());
        }
    }
}
